package com.ks.core.framework.cpsupload.demos.orderpayinvoice.orderhandler;

import com.ks.core.framework.cpsupload.demos.orderpayinvoice.constant.OrderStatus;
import com.ks.core.framework.cpsupload.demos.orderpayinvoice.constant.OrderType;
import com.ks.core.framework.cpsupload.demos.orderpayinvoice.constant.PaymentType;
import lombok.Data;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

// 订单基类
@Data
public abstract class Order {
    private String orderId;
    private OrderType orderType;
    private String itemId; // 套餐ID/房型ID/路线ID
    private BigDecimal amount;
    private OrderStatus status = OrderStatus.PENDING_PAYMENT;
    private boolean invoiceIssued;
    
    // 支付记录（支持多次支付）
    private List<PaymentRecord> paymentRecords = new ArrayList<>();
    
    // 退款记录
    private List<RefundRecord> refundRecords = new ArrayList<>();
    
    public abstract void reduceInventory();
    public abstract void increaseInventory();
    
    // 添加支付记录
    public void addPaymentRecord(PaymentType paymentType, BigDecimal amount, String transactionId) {
        paymentRecords.add(new PaymentRecord(paymentType, amount, transactionId));
        updateOrderStatus();
    }
    
    // 添加退款记录
    public void addRefundRecord(PaymentType paymentType, BigDecimal amount, String transactionId) {
        refundRecords.add(new RefundRecord(paymentType, amount, transactionId));
        updateOrderStatus();
    }
    
    // 更新订单状态
    private void updateOrderStatus() {
        BigDecimal paidAmount = paymentRecords.stream()
            .map(PaymentRecord::getAmount)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        BigDecimal refundedAmount = refundRecords.stream()
            .map(RefundRecord::getAmount)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        if (paidAmount.compareTo(amount) < 0) {
            status = paidAmount.compareTo(BigDecimal.ZERO) > 0 ? 
                    OrderStatus.PARTIALLY_PAID : 
                    OrderStatus.PENDING_PAYMENT;
        } else if (refundedAmount.compareTo(BigDecimal.ZERO) > 0) {
            status = refundedAmount.compareTo(paidAmount) == 0 ? 
                    OrderStatus.REFUNDED : 
                    OrderStatus.PARTIALLY_REFUNDED;
        } else {
            status = OrderStatus.PAID;
        }
        
        // 触发状态处理
        OrderStateManager.handleStateChange(this);
    }
    
    // Getters/Setters
}